package dsk.demo.miaosha.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dsk.demo.miaosha.demo.exception.GlobalException;
import dsk.demo.miaosha.demo.mapper.UserMapper;
import dsk.demo.miaosha.demo.pojo.User;
import dsk.demo.miaosha.demo.service.IUserService;
import dsk.demo.miaosha.demo.utils.CookieUtil;
import dsk.demo.miaosha.demo.utils.MD5Util;
import dsk.demo.miaosha.demo.utils.UUIDUtil;
import dsk.demo.miaosha.demo.utils.ValidatorUtil;
import dsk.demo.miaosha.demo.vo.LoginVo;
import dsk.demo.miaosha.demo.vo.RespBean;
import dsk.demo.miaosha.demo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-07-03
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录服务
     * @param loginVo
     * @return
     */
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //判断用户是否存在
        User user = userMapper.selectById(mobile);
        if (user == null) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //判断密码是否正确
        if (!MD5Util.fromPassToDBPass(loginVo.getPassword(),user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //生成cookie
        String token = UUIDUtil.uuid();
//        request.getSession().setAttribute("ticket",user);
        redisTemplate.opsForValue().set("user:" + token,user);
        CookieUtil.setCookie(request,response,"userTicket",token);
        return RespBean.success(token);

    }

    @Override
    public User getUserByCookie(String suerTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(suerTicket)) {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + suerTicket);
        if (null != user) {
            CookieUtil.setCookie(request,response,"userTicket",suerTicket);
        }
        return user;
    }
}
